package com.xindaoapp.happypet.fragments;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.ChooseAreaDialog;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.api.ConstantsValue;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.AreaInfo;
import com.xindaoapp.happypet.bean.BaseEntity;
import com.xindaoapp.happypet.bean.UploadInfo;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;
import com.xindaoapp.happypet.utils.ProgressHUD;

/**
 * 用户信息
 * 
 * @author chenghao
 * 
 */
public class MyInfoFragment extends BaseFragment implements OnClickListener {
    protected static final int SUCCESS = 10;
    protected static final int FAIL = 20;

    private ImageView vIcon;
    private List<AreaInfo> mAreaInfos;
    private TextView tv_sex, tv_area;
    private SQLiteDatabase db;

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    mActivity.sendBroadcast(new Intent(Constants.KEY_ACTID));
                    // Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
                    Bitmap decodeFile =
                            BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()
                                    .getAbsolutePath() + "/happypet/usericon/temp.jpg");
                    vIcon.setImageBitmap(decodeFile);
                    break;
                case FAIL:
                    // File f =
                    // new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    // + "/happypet/usericon/temp.jpg");
                    // if (f.exists()) {
                    // f.delete();
                    // }
                    // Toast.makeText(getActivity(), "头像修改失败", Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }
        };
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        CommonUtil.mkFiledir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/happypet/usericon");
        imageUri = Uri.parse(IMAGE_FILE_LOCATION);
        return inflater.inflate(R.layout.fragment_myinfo, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (UserState.getUser() != null) {
            ((TextView) getView().findViewById(R.id.user_name))
                    .setText(UserState.getUser().username);
            ImageLoader.getInstance().displayImage(UserState.getUser().userface,
                    ((ImageView) getView().findViewById(R.id.user_icon)));
            ((TextView) getView().findViewById(R.id.userinfo_username))
                    .setText(UserState.getUser().username);
            ((TextView) getView().findViewById(R.id.userinfo_mail))
                    .setText(UserState.getUser().email);
            ((TextView) getView().findViewById(R.id.userinfo_niuniu))
                    .setText(UserState.getUser().niuniu);

            if (UserState.getUser().gender.equals("1")) {
                ((TextView) getView().findViewById(R.id.userinfo_sex)).setText("男");
            } else if (UserState.getUser().gender.equals("2")) {
                ((TextView) getView().findViewById(R.id.userinfo_sex)).setText("女");
            } else {
                ((TextView) getView().findViewById(R.id.userinfo_sex)).setText("未知");
            }

            ((TextView) getView().findViewById(R.id.userinfo_area))
                    .setText(UserState.getUser().province + " " + UserState.getUser().city + " "
                            + UserState.getUser().area);

        }
    }

    @Override
    protected void initEvents(View view) {
        super.initEvents(view);
        mAreaInfos = initSql();
        (view.findViewById(R.id.userinfo_logout)).setOnClickListener(this);
        (view.findViewById(R.id.back)).setOnClickListener(this);
        (view.findViewById(R.id.lay_sex)).setOnClickListener(this);
        (view.findViewById(R.id.lay_area)).setOnClickListener(this);
        vIcon.setOnClickListener(this);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        vIcon = (ImageView) view.findViewById(R.id.user_icon);
        tv_area = (TextView) view.findViewById(R.id.userinfo_area);
        tv_sex = (TextView) view.findViewById(R.id.userinfo_sex);
        // initTopBg(view);
    }

    private void initTopBg(View view) {
        LayoutParams params =
                new LayoutParams(CommonParameter.sScreenWidth,
                        CommonParameter.sScreenWidth * 327 / 640);
        view.findViewById(R.id.r_top).setLayoutParams(params);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.userinfo_logout:
                // new LoginManager(mActivity).logout();
                // getActivity().finish();
                break;
            case R.id.user_icon:
                showDialog();
                break;
            case R.id.back:
                // Intent intent = new Intent();
                // getActivity().setResult(Activity.RESULT_OK, intent);
                getActivity().finish();
                break;
            case R.id.lay_sex:
                showChooseSexDialog();
                break;
            case R.id.lay_area:
                ChooseAreaDialog dialog =
                        new ChooseAreaDialog(getActivity(), R.style.Edit_Count_Dialog, mAreaInfos,
                                new IRequest<KeyValuePair<int[], String[]>>() {

                                    @Override
                                    public void request(KeyValuePair<int[], String[]> t) {
                                        final StringBuilder area = new StringBuilder();
                                        area.append(t.second[0] + " ");
                                        area.append(t.second[1] + " ");
                                        area.append(t.second[2]);
                                        final String[] strs = new String[3];
                                        strs[0] = t.second[0];
                                        strs[1] = t.second[1];
                                        strs[2] = t.second[2];
                                        // provincesIDs = t.first;
                                        // TODO 请求接口,修改地址
                                        final ProgressHUD pHud1 =
                                                ProgressHUD.show(getActivity(), "地址修改中...", true,
                                                        true, null);
                                        HappyPetApplication
                                                .get()
                                                .getMoccaApi()
                                                .getChangeArea(t.second[0], t.second[1],
                                                        t.second[2], new IRequest<BaseEntity>() {

                                                            @Override
                                                            public void request(BaseEntity t) {
                                                                if (null != pHud1
                                                                        && pHud1.isShowing()) {
                                                                    pHud1.dismiss();
                                                                }
                                                                if (t != null) {
                                                                    if (t.getResult().equals("0")) {
                                                                        UserState.getUser().province =
                                                                                strs[0];
                                                                        UserState.getUser().city =
                                                                                strs[1];
                                                                        UserState.getUser().area =
                                                                                strs[2];
                                                                        tv_area.setText(area);

                                                                    } else {
                                                                        Toast.makeText(
                                                                                getActivity(),
                                                                                t.getMsg(),
                                                                                Toast.LENGTH_SHORT)
                                                                                .show();
                                                                    }
                                                                } else {
                                                                    Toast.makeText(
                                                                            getActivity(),
                                                                            getResources()
                                                                                    .getString(
                                                                                            R.string.net_error),
                                                                            Toast.LENGTH_SHORT)
                                                                            .show();
                                                                }
                                                            }
                                                        });
                                    }
                                });
                dialog.show();
                break;
            default:
                break;
        }
    }

    private void showChooseSexDialog() {

        ChooseSexDialog dialog =
                new ChooseSexDialog(getActivity(), R.style.Edit_Count_Dialog,
                        new IRequest<KeyValuePair<Integer, String>>() {

                            @Override
                            public void request(KeyValuePair<Integer, String> t) {
                                // TODO Auto-generated method stub
                                goChangeSex(t.second.equals("男") ? 1 : 2);
                            }

                        });
        dialog.show();

        // final AlertDialog dialog = new Builder(mActivity).create();
        // View view = View.inflate(mActivity, R.layout.layout_choosesex, null);
        // View tv_nan = view.findViewById(R.id.tv_nan);
        // View tv_nv = view.findViewById(R.id.tv_nv);
        // dialog.setView(view);
        // dialog.setCancelable(false);
        // dialog.setCanceledOnTouchOutside(true);
        // tv_nan.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // goChangeSex(1);
        // dialog.dismiss();
        // }
        // });
        // tv_nv.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // goChangeSex(2);
        // dialog.dismiss();
        // }
        // });
        // dialog.setOnCancelListener(new OnCancelListener() {
        // @Override
        // public void onCancel(DialogInterface dialog) {
        // dialog.dismiss();
        // }
        // });
        // view.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View arg0) {
        // // TODO Auto-generated method stub
        // dialog.dismiss();
        // }
        // });
        //
        // dialog.show();
    }

    protected void goChangeSex(final int i) {
        final ProgressHUD pHud1 = ProgressHUD.show(getActivity(), "性别修改中...", true, true, null);
        HappyPetApplication.get().getMoccaApi()
                .getChangeSex(String.valueOf(i), new IRequest<BaseEntity>() {

                    @Override
                    public void request(BaseEntity t) {

                        if (null != pHud1 && pHud1.isShowing()) {
                            pHud1.dismiss();
                        }
                        if (t != null) {
                            if (t.getResult().equals("0")) {
                                UserState.getUser().gender = String.valueOf(i);
                                tv_sex.setText(i == 1 ? "男" : "女");
                            } else {
                                Toast.makeText(getActivity(), t.getMsg(), Toast.LENGTH_SHORT)
                                        .show();
                            }
                        } else {
                            Toast.makeText(getActivity(),
                                    getResources().getString(R.string.net_error),
                                    Toast.LENGTH_SHORT).show();
                        }


                    }
                });
    }

    @Override
    protected boolean showBottomTabBar() {
        return false;
    }

    @Override
    protected boolean showTopTabBar() {
        return false;
    }

    // data
    private static final String TAG = "MainActivity";
    private static final int TAKE_BIG_PICTURE = 1;
    private static final int TAKE_SMALL_PICTURE = 2;
    private static final int CROP_BIG_PICTURE = 3;
    private static final int CROP_SMALL_PICTURE = 4;
    private static final int CHOOSE_BIG_PICTURE = 5;
    private static final int CHOOSE_SMALL_PICTURE = 6;
    private static final String IMAGE_FILE_LOCATION = "file:///"
            + Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/happypet/usericon/temp.jpg";
    private Uri imageUri;// to store the big bitmap

    // views
    // private ImageView imageView;

    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    private void showDialog() {
        final AlertDialog dialog = new Builder(mActivity).create();
        View view = View.inflate(mActivity, R.layout.pic_selector, null);
        View pic_selector_camera = view.findViewById(R.id.pic_selector_camera);
        View pic_selector_album = view.findViewById(R.id.pic_selector_album);
        dialog.setCanceledOnTouchOutside(true);
        pic_selector_camera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startCapture();
                dialog.dismiss();
            }
        });
        pic_selector_album.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startChoosePic();
                dialog.dismiss();
            }
        });
        dialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    private void uploadPIC() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("uid", UserState.getUserUid());
        params.addBodyParameter("img", new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/happypet/usericon/temp.jpg"));
        HttpUtils utils = new HttpUtils();
        if (ConstantsValue.cookieStore != null) {
            utils.configCookieStore(ConstantsValue.cookieStore);
        }
        final ProgressHUD progressHUD = ProgressHUD.show(mActivity, "头像修改中...", true, true, null);
        utils.send(HttpMethod.POST, Address.CHANGEPIC, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    if (null != progressHUD && progressHUD.isShowing()) {
                        progressHUD.dismiss();
                    }
                    UploadInfo picinfo = JSON.parseObject(responseInfo.result, UploadInfo.class);
                    if (picinfo.getResult().equals("0")) {
                        handler.sendEmptyMessage(SUCCESS);
                        // 清 缓存
                        ImageLoader.getInstance().clearMemoryCache();
                        ImageLoader.getInstance().clearDiscCache();
                    } else {
                        Toast.makeText(mActivity, "头像修改失败", Toast.LENGTH_SHORT).show();
                        handler.sendEmptyMessage(FAIL);
                    }
                    // if (picinfo.getResult().equals("5")) {
                    // handler.sendEmptyMessage(FAIL);
                    // }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                if (null != progressHUD && progressHUD.isShowing()) {
                    progressHUD.dismiss();
                }
                Toast.makeText(mActivity, "头像修改失败", Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessage(FAIL);
                // Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap =
                    BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(
                            uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    private void startCapture() {
        // capture a big bitmap and store it in Uri
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// action is capture
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_BIG_PICTURE);
    }

    private void startChoosePic() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false); // no face detection
        startActivityForResult(intent, CHOOSE_BIG_PICTURE);
    }

    /** Handle click events */
    // public void onClick(View v) {
    // Intent intent = null;
    // switch (v.getId()) {
    // case R.id.buttonTakeBigPicture:
    // if (imageUri == null) {
    // Log.e(TAG, "image uri can't be null");
    // }
    // // capture a big bitmap and store it in Uri
    // intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// action is capture
    // intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    // startActivityForResult(intent, TAKE_BIG_PICTURE);
    // break;
    // case R.id.buttonTakeSmallPicture:
    // intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// action is capture
    // intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    // startActivityForResult(intent, TAKE_SMALL_PICTURE);
    // break;
    // case R.id.buttonChooseBigPicture:
    // intent = new Intent(Intent.ACTION_GET_CONTENT, null);
    // intent.setType("image/*");
    // intent.putExtra("crop", "true");
    // intent.putExtra("aspectX", 2);
    // intent.putExtra("aspectY", 1);
    // intent.putExtra("outputX", 600);
    // intent.putExtra("outputY", 300);
    // intent.putExtra("scale", true);
    // intent.putExtra("return-data", false);
    // intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    // intent.putExtra("noFaceDetection", false); // no face detection
    // startActivityForResult(intent, CHOOSE_BIG_PICTURE);
    // break;
    // case R.id.buttonChooseSmallPicture:
    // intent = new Intent(Intent.ACTION_GET_CONTENT, null);
    // intent.setType("image/*");
    // intent.putExtra("crop", "true");
    // intent.putExtra("aspectX", 2);
    // intent.putExtra("aspectY", 1);
    // intent.putExtra("outputX", 200);
    // intent.putExtra("outputY", 100);
    // intent.putExtra("scale", true);
    // intent.putExtra("return-data", true);
    // intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    // intent.putExtra("noFaceDetection", true); // no face detection
    // startActivityForResult(intent, CHOOSE_SMALL_PICTURE);
    // break;
    // default:
    // break;
    // }
    // }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {// result is not correct
            Log.e(TAG, "requestCode = " + requestCode);
            Log.e(TAG, "resultCode = " + resultCode);
            Log.e(TAG, "data = " + data);
            return;
        } else {
            switch (requestCode) {
                case TAKE_BIG_PICTURE:
                    Log.d(TAG, "TAKE_BIG_PICTURE: data = " + data);// it seems to be null
                    // TODO sent to crop
                    cropImageUri(imageUri, 300, 300, CROP_BIG_PICTURE);
                    // or decode as bitmap and display it
                    // if(imageUri != null){
                    // Bitmap bitmap = decodeUriAsBitmap(imageUri);
                    // imageView.setImageBitmap(bitmap);
                    // }
                    break;
                case CROP_BIG_PICTURE:// from crop_big_picture
                    Log.d(TAG, "CROP_BIG_PICTURE: data = " + data);// it seems to be null
                    if (imageUri != null) {
                        Bitmap bitmap = decodeUriAsBitmap(imageUri);
                        // imageView.setImageBitmap(bitmap);
                        uploadPIC();
                    }
                    break;
                case TAKE_SMALL_PICTURE:
                    Log.i(TAG, "TAKE_SMALL_PICTURE: data = " + data);
                    // TODO sent to crop
                    cropImageUri(imageUri, 300, 300, CROP_SMALL_PICTURE);
                    // or decode as bitmap and display it
                    // if(imageUri != null){
                    // Bitmap bitmap = decodeUriAsBitmap(imageUri);
                    // imageView.setImageBitmap(bitmap);
                    // }
                    break;
                case CROP_SMALL_PICTURE:
                    if (imageUri != null) {
                        Bitmap bitmap = decodeUriAsBitmap(imageUri);
                        // imageView.setImageBitmap(bitmap);
                    } else {
                        Log.e(TAG, "CROP_SMALL_PICTURE: data = " + data);
                    }
                    break;
                case CHOOSE_BIG_PICTURE:
                    Log.d(TAG, "CHOOSE_BIG_PICTURE: data = " + data);// it seems to be null
                    if (imageUri != null) {
                        Bitmap bitmap = decodeUriAsBitmap(imageUri);
                        // imageView.setImageBitmap(bitmap);
                        uploadPIC();
                    }
                    break;
                case CHOOSE_SMALL_PICTURE:
                    if (data != null) {
                        Bitmap bitmap = data.getParcelableExtra("data");
                        // imageView.setImageBitmap(bitmap);
                    } else {
                        Log.e(TAG, "CHOOSE_SMALL_PICTURE: data = " + data);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private List<AreaInfo> initSql() {
        File file = new File("/data/data/" + getActivity().getPackageName() + "/files/area.db");
        if (!file.exists()) {
            new File("/data/data/" + getActivity().getPackageName() + "/files").mkdir();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            InputStream is = getResources().openRawResource(R.raw.area);
            inputstreamtofile(is, file);
        }
        db =
                SQLiteDatabase.openDatabase(file.getAbsolutePath(), null,
                        SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        // 对数据库进行操作
        List<AreaInfo> provience = getAreaInfos(db, "provience");
        Map<Integer, List<AreaInfo>> city = getAreaInfoMaps(db, "city");
        Map<Integer, List<AreaInfo>> area = getAreaInfoMaps(db, "area");
        // 讲区县添加到市
        for (int i = 0; i < provience.size(); i++) {
            AreaInfo info = provience.get(i);
            info.list = city.get(provience.get(i).id);
            for (int j = 0; j < info.list.size(); j++) {
                info.list.get(j).list = area.get(info.list.get(j).id);
            }
        }
        return provience;
    }

    /**
     * 流转文件
     * 
     * @param ins
     * @param file
     */
    public static void inputstreamtofile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("UseSparseArrays")
    private Map<Integer, List<AreaInfo>> getAreaInfoMaps(SQLiteDatabase db, String tableName) {
        Map<Integer, List<AreaInfo>> map = new HashMap<Integer, List<AreaInfo>>();
        Cursor provience = db.query(tableName, null, null, null, null, null, null);
        if (provience.moveToFirst()) {
            do {
                AreaInfo info = new AreaInfo();
                info.id = provience.getInt(provience.getColumnIndex("id"));
                info.parentid = provience.getInt(provience.getColumnIndex("parentid"));
                info.name = provience.getString(provience.getColumnIndex("name"));
                if (map.containsKey(info.parentid)) {
                    map.get(info.parentid).add(info);
                } else {
                    List<AreaInfo> list = new ArrayList<AreaInfo>();
                    list.add(info);
                    map.put(info.parentid, list);
                }
            } while (provience.moveToNext());
        }
        return map;
    }

    private List<AreaInfo> getAreaInfos(SQLiteDatabase db, String tableName) {
        List<AreaInfo> list = new ArrayList<AreaInfo>();
        Cursor provience = db.query(tableName, null, null, null, null, null, null);
        if (provience.moveToFirst()) {
            do {
                AreaInfo info = new AreaInfo();
                info.id = provience.getInt(provience.getColumnIndex("id"));
                info.parentid = provience.getInt(provience.getColumnIndex("parentid"));
                info.name = provience.getString(provience.getColumnIndex("name"));
                list.add(info);
            } while (provience.moveToNext());
        }
        return list;
    }

    class ChooseSexDialog extends Dialog {

        private View tv_nan, tv_nv;
        private int layer;
        private Context mContext;
        private IRequest iRequest;

        public ChooseSexDialog(Context context) {
            super(context);
        }

        public ChooseSexDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        public ChooseSexDialog(Context context, int theme,
                IRequest<KeyValuePair<Integer, String>> iRequest) {
            super(context, theme);
            mContext = context;
            this.iRequest = iRequest;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout_choosesex);
            tv_nan = findViewById(R.id.tv_nan);
            tv_nv = findViewById(R.id.tv_nv);
            tv_nan.setOnClickListener(mOnClickListener);
            tv_nv.setOnClickListener(mOnClickListener);
            findViewById(R.id.close).setOnClickListener(mOnClickListener);
        }

        private final View.OnClickListener mOnClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.tv_nan:
                        iRequest.request(new KeyValuePair<Integer, String>(0, "男"));
                        dismiss();
                        break;
                    case R.id.tv_nv:
                        iRequest.request(new KeyValuePair<Integer, String>(0, "女"));
                        dismiss();
                        break;
                    case R.id.close:
                        dismiss();
                        break;
                    default:
                        break;
                }
            }
        };

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (db != null) {
            db.close();
        }
    }



}
